package com.kehutong.payfees.service;

import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.ChargeChoose;
import com.kehutong.payfees.entity.ChargeInstrumentType;
import com.kehutong.payfees.entity.ChargeUserInstrument;
import com.kehutong.payfees.util.BasicClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.util.List;

@WebService("/payfees/charge/instrument/type")
public class ChargeInstrumentTypeServiceImpl {

    @Inject
    private JdbcSession sqlSession;
    @Inject
    private BasicClient basicClient;

    public Object list(JSONObject jsonObject) {
        return sqlSession.findPage(ChargeInstrumentType.class)
                        .eq(jsonObject, "communityNo", "name")
                        .eq("deleted", false)
                        .order("createTime", "desc")
                        .page(jsonObject)
                        .exe();
    }

    public Object listAll(JSONObject jsonObject) {
        if(Objects.isEmpty(jsonObject.getString("communityNo"))){
            return null;
        }

        List<ChargeInstrumentType> list = sqlSession.findArray(ChargeInstrumentType.class)
                .eq(jsonObject, "communityNo")
                .eq("deleted", false).exe();

        return list;
    }

    public Object get(String id) {
        final ChargeInstrumentType chargeInstrumentType = Pool.get(ChargeInstrumentType.class, id);
        if (Objects.isNull(chargeInstrumentType)) {
            return Result.error(-1, "该类型不存在！");
        }

        return chargeInstrumentType;
    }

    public Object save(Token token, ChargeInstrumentType chargeInstrumentType) throws Exception {
        ChargeInstrumentType resultChargeInstrumentType = sqlSession.findOne(ChargeInstrumentType.class)
                .eq("communityNo", chargeInstrumentType.getCommunityNo())
                .eq("name", chargeInstrumentType.getName())
                .eq("deleted", false).exe();

        if (Objects.nonNull(resultChargeInstrumentType)) {
            return Result.error(-1, "该类型已存在！");
        }

        setDepartmentNo(chargeInstrumentType, token.getCompanyNo());

        chargeInstrumentType.setDeleted(false);
        sqlSession.insert(chargeInstrumentType);
        return Result.success();
    }

    public Object update(Token token, ChargeInstrumentType chargeInstrumentType) throws Exception {
        ChargeInstrumentType resultChargeInstrumentType = sqlSession.findOne(ChargeInstrumentType.class)
                .noEq("id", chargeInstrumentType.getId())
                .eq("communityNo", chargeInstrumentType.getCommunityNo())
                .eq("name", chargeInstrumentType.getName())
                .eq("deleted", false).exe();

        if (Objects.nonNull(resultChargeInstrumentType)) {
            return Result.error(-1, "该类型已存在！");
        }

        List<ChargeChoose> chooses = sqlSession.findArray(ChargeChoose.class)
                .eq("instrumentTypeId", chargeInstrumentType.getId())
                .exe();
        chooses.forEach(choose -> {
            choose.setFeeTypeName(chargeInstrumentType.getName());
            sqlSession.updateById(choose);
        });

        setDepartmentNo(chargeInstrumentType, token.getCompanyNo());

        sqlSession.updateById(chargeInstrumentType);
        return Result.success();
    }

    private void setDepartmentNo(ChargeInstrumentType chargeInstrumentType, String companyNo) throws Exception {
        JSONObject community = basicClient.getCommunityById(companyNo,
                chargeInstrumentType.getCommunityNo());
        if(Objects.nonEmpty(community)){
            String parent_id = community.getString("parent_id");
            if(Objects.nonEmpty(parent_id)){
                chargeInstrumentType.setDepartmentNo(parent_id);
            }
            JSONArray parent_ids = community.getJSONArray("parent_ids");
            if(Objects.nonEmpty(parent_ids)){
                List<String> departmentNos = JSONObject.parseArray(parent_ids.toJSONString(), String.class);
                chargeInstrumentType.setDepartmentNos(departmentNos);
            }
        }
    }

    public Object delete(String id) {
        final ChargeInstrumentType chargeInstrumentType = Pool.get(ChargeInstrumentType.class, id);
        if (Objects.nonNull(chargeInstrumentType)) {
            List<ChargeUserInstrument> chargeUserInstruments = sqlSession.findArray(ChargeUserInstrument.class)
                    .eq("instrumentTypeId", chargeInstrumentType.getId())
                    .eq("deleted", false).exe();
            if (Objects.nonNull(chargeUserInstruments) && chargeUserInstruments.size() != 0) {
                return Result.error(0, "该仪表类型下存在入户表，不可删除！");
            }
            chargeInstrumentType.setDeleted(true);
            sqlSession.updateById(chargeInstrumentType);
            return Result.success();
        }

        return Result.error(0, "该仪表类型不存在");
    }
}
